package rule07;

import java.util.Arrays;

/** 
 * @author ChangLiang
 * @date 2020/3/16
 */
public class StackV2 {

    private Object[] elements;

    private int size = 0;

    private static final int DEFAULT_INITIAL_CAPACITY = 5;

    public StackV2(){
        elements = new Object[DEFAULT_INITIAL_CAPACITY];
    }

    public void push(Object object) {
        ensureCapacity();
        elements[size++] = object;
        size++;
    }

    private void ensureCapacity() {
        if (elements.length == size) {
            elements = Arrays.copyOf(elements, 2 * size + 1);
        }
    }

    public Object pop() {
        if (size == 0) {
            throw new IllegalArgumentException();
        }
        Object e = elements[size];
        // 置为null 防止内存泄漏
        elements[size]=null;
        size--;
        return e;
    }
}
